package com.nihome.entershopinfo.fragments;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nihome.entershopinfo.Constants;
import com.nihome.entershopinfo.R;
import com.nihome.entershopinfo.adapter.ChildShopLogAdapter;
import com.nihome.entershopinfo.adapter.ExpandsLogAdapter;
import com.nihome.entershopinfo.application.SysApplication;
import com.nihome.entershopinfo.dialog.LoadingDialog;
import com.nihome.entershopinfo.entity.User;
import com.nihome.entershopinfo.entity.response.ExpandsLogRes;
import com.nihome.entershopinfo.entity.response.PageResponse;
import com.nihome.entershopinfo.entity.response.ResponseBase;
import com.nihome.entershopinfo.ui.HomePageActivity;
import com.nihome.entershopinfo.utils.Log;
import com.nihome.entershopinfo.utils.RequestAPI;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Carson on 2017/10/25.
 */
public class ChildShopLogFragment extends Fragment {
    private static final String TAG = "ChildShopLogFragment";

    private static final int NUM = 20;    //设置条目数
    private int currentPage = 0;         //当前页
    private int countPage;               //总页数

    private Context mContext;
    private User mUser;
    private Gson mGson;
    private LoadingDialog dialog;

    private PullToRefreshListView mListView;
    private List<ExpandsLogRes> expandsLogResList;
    private ChildShopLogAdapter adapter;


    private TextView addChildShop;

    private ExpandsLogRes parentLog;
    private String parentAuditId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mUser = SysApplication.getInstance().getmUser();
        mGson = new Gson();
        dialog = new LoadingDialog(mContext);

        parentLog = getArguments().getParcelable("parentLog");
        parentAuditId = parentLog.getBasicInfoResponseDTO().getAuditId();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child_shop, container, false);
        mListView = (PullToRefreshListView) view.findViewById(R.id.child_shop_list);
        addChildShop = (TextView) view.findViewById(R.id.add_child_shop);

        addChildShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initShopData(1);
            }
        });
        view.findViewById(R.id.look_account_detail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((HomePageActivity) getActivity()).lookDetailLog(parentLog);
            }
        });
        view.findViewById(R.id.child_shop_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((HomePageActivity) getActivity()).backClick();
            }
        });

        getExpandsLog();
        return view;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            parentLog = getArguments().getParcelable("parentLog");
            parentAuditId = parentLog.getBasicInfoResponseDTO().getAuditId();
            getExpandsLog();
        }
    }


    private void initList(){
        if (adapter == null) {
            adapter = new ChildShopLogAdapter(mContext, expandsLogResList, mHandler);
            mListView.setAdapter(adapter);
        }else {
            adapter.setData(expandsLogResList);
            adapter.notifyDataSetChanged();
        }
    }




    private void getExpandsLog(){
        dialog.show(getString(R.string.load_text));
        String url = RequestAPI.FIND_CHILD_SHOP + parentAuditId + "?page="+currentPage+"&size="+NUM;
        Log.e(TAG, url);
        OkHttpUtils.get().url(url).build().execute(new ExpandsLogCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mListView.onRefreshComplete();
                Log.e(TAG, e + "");
                dialog.dismiss();
                if (e instanceof UnknownHostException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof IOException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBase<PageResponse> response, int id) {
                mListView.onRefreshComplete();
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        countPage = response.getResult().getTotalPage();
                        currentPage = response.getResult().getCurrentPage();
                        if (currentPage > 0){
                            expandsLogResList.addAll(response.getResult().getAuditOtherInfoResponseDTOList());
                        } else {
                            expandsLogResList = response.getResult().getAuditOtherInfoResponseDTOList();
                        }

                        initList();
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class ExpandsLogCallback extends Callback<ResponseBase<PageResponse>> {
        @Override
        public ResponseBase<PageResponse> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<PageResponse>>(){}.getType();
            ResponseBase<PageResponse> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }



    private void initShopData(int type){
        String url = RequestAPI.INIT_SHOP_DATA_URL + "?source="+ type +"&marketerId="+mUser.getUserId();
        OkHttpUtils.get().url(url).build().execute(new InitShopDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, e + "");
                if (e instanceof UnknownHostException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof IOException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBase<String> response, int id) {
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        SysApplication.getInstance().setAuditId(response.getResult());
                        ((HomePageActivity)getActivity()).xcxClick_chainChild(parentAuditId, new ExpandsLogRes());
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class InitShopDataCallback extends Callback<ResponseBase<String>>{
        @Override
        public ResponseBase<String> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<String>>(){}.getType();
            ResponseBase<String> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }





    private int position;
    public Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case ExpandsLogAdapter.LOOK:
                    position = message.arg1;
                    short status = expandsLogResList.get(position).getOtherInfoResponseDTO().getAuditStatus();
                    if (status == 101 || status == 202) {
                        ((HomePageActivity)getActivity()).xcxClick_chainChild(parentAuditId, expandsLogResList.get(position));
                    }else {
                        ((HomePageActivity)getActivity()).lookDetailLog(expandsLogResList.get(position));
                    }

                    break;
                case ExpandsLogAdapter.VOUCHER:
                    position = message.arg1;
                    ((HomePageActivity)getActivity()).moneyVoucherBtn(expandsLogResList.get(position));
                    break;
            }
            return false;
        }
    });
}
